package com.firefly.app.cordova.plugins;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;

import android.content.Context;
import android.view.inputmethod.InputMethodManager;

import com.firefly.mobile.app.util.SytLog;

public class SoftKeyBoardPlugin extends CordovaPlugin {

    public SoftKeyBoardPlugin() {
    }

    public void showKeyBoard() {
      InputMethodManager mgr = (InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
      mgr.showSoftInput(webView.getView(), InputMethodManager.SHOW_IMPLICIT);

      ((InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(webView.getView(), 0);
    }

    public void hideKeyBoard() {
      InputMethodManager mgr = (InputMethodManager) cordova.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
      mgr.hideSoftInputFromWindow(webView.getView().getWindowToken(), 0);
    }

    public boolean isKeyBoardShowing() {
      int heightDiff = webView.getView().getRootView().getHeight() - webView.getView().getHeight();
      return (100 < heightDiff); // if more than 100 pixels, its probably a keyboard...
    }

    @Override  
    public boolean execute(final String action,final  org.json.JSONArray args,  
    		final  CallbackContext callbackContext) throws org.json.JSONException {
        SytLog.i("softKeyBoardPlugin", action);  
        
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
					execPlugin(action, args, callbackContext);
				} catch (Exception e) {
					e.printStackTrace();
					SytLog.e("softKeyBoardPlugin", "插件调用出错");
					callbackContext.error("插件调用出错");
				}
            }
        });
        
        return true;  
  
    }  
    
    private void execPlugin(final String action,final  org.json.JSONArray args,  
    		final CallbackContext callbackContext) throws org.json.JSONException {
        try {
        	
        	if (action.equals("show")) {
      	      this.showKeyBoard();
      	      callbackContext.success("done");
      	    }
      	    else if (action.equals("hide")) {
      	      this.hideKeyBoard();
      	      callbackContext.success();
      	    }
      	    else if (action.equals("isShowing")) {
      	      callbackContext.success(Boolean.toString(this.isKeyBoardShowing()));
      	    }
		} catch (Exception e) {
			callbackContext.success("01"); 
			e.printStackTrace();
			SytLog.e("softKeyBoardPlugin", "调用键盘出错");
		}  
    }
}

